//
//  GameControllerViewController.m
//  BDDynamicGridViewDemo
//
//  Created by liyang on 7/30/12.
//  Copyright (c) 2012 Bluedot. All rights reserved.
//

#define UIAlertViewTag_NewGame 0x1


#import "GameControllerViewController.h"
#import "CardViewController.h"
//#import "NSString+NSStringEx.h"

@interface GameControllerViewController ()

@end

@implementation GameControllerViewController

static GameControllerViewController * s_GameController = nil;

+ (GameControllerViewController*)sharedGameControllerInstance
{
    @synchronized([GameControllerViewController class])
    {
        if (s_GameController == nil)
            s_GameController = [[GameControllerViewController alloc] init];
    }
	return s_GameController;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self LoadGame];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    updateTimer = [NSTimer timerWithTimeInterval:3
                                          target:self
                                        selector:@selector(_updateTimerFired:)
                                        userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:updateTimer forMode:NSDefaultRunLoopMode];	
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    if (updateTimer != nil)
	{
		[updateTimer invalidate];
		updateTimer = nil;
	}
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

-(void) _updateTimerFired:(NSTimer*)theTimer
{
    if ([self GetUserGold] < MAX_TimerGold) {
        [self SetUserGold:[self GetUserGold]+1];
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}



-(IBAction) NewGame
{
    int usergold = [self GetUserGold];
    if(usergold >= 10)
    {
        UIAlertView * al = [[UIAlertView alloc] initWithTitle:nil message:@"花费5点墨水开始挑战！" delegate:self cancelButtonTitle:@"NO" otherButtonTitles:@"YES", nil];
        al.tag = UIAlertViewTag_NewGame;
        [al show];
    }
    else
    {
        [[[UIAlertView alloc] initWithTitle:nil message:@"您的墨水不够了，请继续等待墨水恢复或者支持我们的广告。" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil] show];
    }
}

-(IBAction) ShowGirl
{
    BDViewController * sg = [[BDViewController alloc] init];
    [self.navigationController pushViewController:sg animated:YES];
}

-(void) SaveGame
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    NSString *savePath = [docDir stringByAppendingPathComponent:GameDEF_Savefile];
    if ([[NSFileManager defaultManager] fileExistsAtPath:savePath]) 
    {
        [[NSFileManager defaultManager] removeItemAtPath:savePath error:nil];
    }

    NSString * scorestring = [NSString stringWithFormat:@"%d,%qu", user_gold, user_passedLevel];
    NSString * md5String = nil; //[scorestring md5];
    NSString * saveString = [NSString stringWithFormat:@"%@,%@", scorestring, md5String];
    
    if (saveString != nil)
    {
        [saveString writeToFile:savePath atomically:YES encoding:(NSUTF8StringEncoding) error:nil];
    }    
}

-(void) LoadGame
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    NSString *savePath = [docDir stringByAppendingPathComponent:GameDEF_Savefile];
    NSString * saveString;
    if ([[NSFileManager defaultManager] fileExistsAtPath:savePath])
    {
        saveString = [NSString stringWithContentsOfFile:savePath encoding:NSUTF8StringEncoding error:nil];
        NSArray * tempa = [saveString componentsSeparatedByString:@","];
        
        if ([tempa count] < 3)
        {
            user_gold = GameDEF_UserGloden_Default;
            user_passedLevel = GameDEF_PassedLevel_Default;
            return;
        }
        user_gold = [[tempa objectAtIndex:0] intValue];
        user_passedLevel = [[tempa objectAtIndex:1] longLongValue];
        NSString * md5string = [tempa objectAtIndex:2];
        NSString * scorestring = [NSString stringWithFormat:@"%d,%qu", user_gold, user_passedLevel];
        NSString * md5String = nil;//[scorestring md5];
        if(NSOrderedSame != [md5String compare:md5string] )
        {
            user_gold = GameDEF_UserGloden_Default;
            user_passedLevel = GameDEF_PassedLevel_Default;
            return;
        }
    }
    else
    {
        user_gold = GameDEF_UserGloden_Default;
        user_passedLevel = GameDEF_PassedLevel_Default;
    }

}

- (int) GetUserGold
{
    return user_gold;
}

- (BOOL) IsPassedLevel:(int)level_index
{
    return (user_passedLevel & (0x01<<level_index))>0;
}

- (void) SetUserGold:(int)ugold
{
    if (ugold >= 0 && ugold < (user_gold+50000))
    {
        user_gold = ugold;
        [self SaveGame];
    }
    
}

- (void) SetUserPassedLevel:(int)level_index
{
    if (level_index < 64 && level_index > 0) 
    {
        user_passedLevel |= (0x1<<level_index);
    }
    [self SaveGame];
}



// Called when a button is clicked. The view will be automatically dismissed after this call returns
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == UIAlertViewTag_NewGame) 
    {
        if (buttonIndex == 1)
        {
            int usergold = [self GetUserGold];
            if (usergold >= 5)
            {
                usergold -= 5;
                
                [[GameControllerViewController sharedGameControllerInstance] SetUserGold:usergold];
                
                CardViewController* card = [[CardViewController alloc] initWithNibName:nil bundle:nil];
                [self.navigationController pushViewController:card animated:YES];
            }
        }
    }
}

// Called when we cancel a view (eg. the user clicks the Home button). This is not called when the user clicks the cancel button.
// If not defined in the delegate, we simulate a click in the cancel button
- (void)alertViewCancel:(UIAlertView *)alertView
{
    
}


@end
